<template>
  <div v-show="isVisible" class="context-menu" :style="{ left: position.x + 'px', top: position.y + 'px' }">
    <div class="menu-container">
      <template v-for="(item, index) in menuItems" :key="index">
        <div class="menu-item" @click="handleMenuClick(item)">
          <span class="menu-label">{{ item.label }}</span>
          <span v-if="item.submenu" class="submenu-arrow" >›</span>
          <div v-if="item.submenu" class="submenu">
          <div v-for="(subItem, subIndex) in item.submenu" :key="subIndex" class="menu-item"
            @click="handleMenuClick(subItem)">
            {{ subItem.label }}
          </div>
        </div>
        </div>

        
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, onMounted, onUnmounted } from 'vue'
import type { MenuItem } from '../cme-mapboxCore/config/rightMenu'

interface Props {
  menuItems: MenuItem[]
}

const props = defineProps<Props>()
const isVisible = ref(false)
const position = ref({ x: 0, y: 0 })

// 在指定位置显示菜单
const showAt = (x: number, y: number) => {
  position.value = { x, y }
  isVisible.value = true
}

// 隐藏菜单
const hide = () => {
  isVisible.value = false
}

// 处理菜单项点击
const handleMenuClick = (item: MenuItem) => {
  if (item.action) {
    item.action()
  }
  hide()
}

// 点击外部关闭菜单
const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as HTMLElement
  if (!target.closest('.context-menu')) {
    hide()
  }
}

// 暴露方法给父组件
defineExpose({
  showAt,
  hide
})

// 添加/移除点击外部监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style lang="scss" scoped>
.context-menu {
  position: fixed;
  z-index: 10;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  min-width: 160px;

  .menu-container {
    // padding: 4px 0;
  }

  .menu-item {
    font-size:14px;
    padding: 6px 14px;
    cursor: pointer;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;

    &:hover {
      background-color: #f5f5f5;

      >.submenu {
        display: block;
      }
    }
  }

  .submenu {
    z-index: 15;
    display: none;
    position: absolute;
    right: -70%;
    top: 0;
    background: white;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
    min-width:120px;
  }

  .submenu-arrow {
    margin-left: 8px;
  }
}
</style>